// 加载导航栏组件
async function loadNavbar() {
    try {
        const response = await fetch('../components/navbar.html');
        const html = await response.text();
        document.getElementById('navbar-container').innerHTML = html;
        initNavbar();
    } catch (error) {
        console.error('加载导航栏失败:', error);
    }
}

// 初始化导航栏状态
function initNavbar() {
    const { isLoggedIn, username } = checkLogin();
    const loginButton = document.getElementById('loginButton');
    const usernameDisplay = document.getElementById('usernameDisplay');

    if (isLoggedIn) {
        loginButton.textContent = '退出';
        usernameDisplay.textContent = `欢迎您，${username}`;
    } else {
        loginButton.textContent = '去登录';
        usernameDisplay.textContent = '未登录';
    }
}

// 处理搜索
function handleSearch() {
    const searchInput = document.getElementById('searchInput');
    const searchTerm = searchInput.value.trim();
    
    if (searchTerm) {
        // 将用户重定向到搜索结果页面
        window.location.href = `home.html?search=${encodeURIComponent(searchTerm)}`;
    }
}

// 处理登录/退出
function handleLoginLogout() {
    const { isLoggedIn } = checkLogin();
    
    if (isLoggedIn) {
        // 退出登录
        localStorage.removeItem('xlsystem_user');
        window.location.reload();
    } else {
        // 跳转到登录页面
        window.location.href = 'login.html';
    }
}

// 跳转到用户中心
function toUserCenter() {
    const userJson = localStorage.getItem('xlsystem_user');
    if (userJson) {
        try {
            const user = JSON.parse(userJson);
            const userId = user.id;
            if (userId) {
                window.location.href = `userCenter.html?userId=${userId}`;
                return;
            }
        } catch (error) {
            console.error('解析用户数据出错:', error);
        }
    }
    window.location.href = 'login.html';
}

// 将函数设置为全局可用
window.handleSearch = handleSearch;
window.handleLoginLogout = handleLoginLogout;
window.toUserCenter = toUserCenter;

// 当DOM加载完成时初始化导航栏
document.addEventListener('DOMContentLoaded', loadNavbar); 